from typing import List, Optional
from uuid import UUID

from sqlalchemy import select, delete
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload

from app.crud.base import CRUDBase
from app.models.doctor_profile import DoctorProfile, DoctorCertificateFile
from app.schemas.user import DoctorProfileCreate


class CRUDDoctorProfile(CRUDBase[DoctorProfile, DoctorProfileCreate, DoctorProfileCreate]):
    async def get_by_user_id(self, db: AsyncSession, *, user_id: str) -> Optional[DoctorProfile]:
        stmt = (
            select(DoctorProfile)
            .options(selectinload(DoctorProfile.certificates))
            .filter(DoctorProfile.user_id == user_id)
        )
        result = await db.execute(stmt)
        return result.scalars().first()

    async def add_certificate_files(
        self,
        db: AsyncSession,
        *,
        profile: DoctorProfile,
        file_ids: List[UUID],
    ) -> DoctorProfile:
        await db.execute(
            delete(DoctorCertificateFile).where(DoctorCertificateFile.profile_id == profile.id)
        )

        for file_id in file_ids:
            db.add(DoctorCertificateFile(profile_id=profile.id, file_id=file_id))

        await db.flush()
        await db.refresh(profile, attribute_names=["certificates"])
        return profile


doctor_profile = CRUDDoctorProfile(DoctorProfile)
